package com.recharge;

import com.recharge.domain.TradeFlow;
import com.recharge.domain.TradeMerchant;
import com.recharge.domain.TradeNotify;
import com.recharge.domain.TradeOrder;
import com.recharge.mapper.*;
import com.recharge.sup.AbsSupChargeService;
import com.recharge.utils.OrderStatus;
import com.recharge.utils.ProcessResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

/**
 * Created by CAOQI on 2016/12/17.
 */
@Service
public class OrderService {

    @Autowired
    private ITradeOrderMapper iTradeOrderMapper;

    @Autowired
    private ITradeFlowMapper iTradeFlowMapper;


    @Autowired
    private TradeNotifyMapper tradeNotifyMapper;

    @Autowired
    private ITradeMerchantMapper iTradeMerchantMapper;

    @Autowired
    private ISalePriceMapper iSalePriceMapper;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * @param merId  商户号
     * @param ispId 运营商
     * @param provinceId 省code
     * @param cityCode 城市code
     * @param chargeNumber 手机号
     * @param chargeMoney 流量值
     * @param merOrderid 商户订单号
     * @param notifyUrl 回调地址
     * @param busiType 省内 全国
     * @param faceValue 面值
     * @param payMoney 成本价
     * @param packageType 包类型
     */
    public void makeOrder(String merId,Short ispId,Short provinceId,String cityCode,String chargeNumber,Long chargeMoney,
                          String merOrderid,String notifyUrl,Short busiType,Long faceValue,BigDecimal payMoney,String packageType,
                          String orderType){

        TradeOrder tradeOrder = new TradeOrder();
        tradeOrder.setMerId(merId);
        tradeOrder.setIspId(ispId);
        tradeOrder.setProvinceId(provinceId);
        tradeOrder.setCityCode(cityCode);
        tradeOrder.setChargeNumber(chargeNumber);
        tradeOrder.setChargeMoney(chargeMoney);
        tradeOrder.setOrderTime(new Date());
        tradeOrder.setMerOrderid(merOrderid);
        tradeOrder.setNotifyUrl(notifyUrl);
        tradeOrder.setBusiType(busiType);
        tradeOrder.setFaceValue(faceValue);
        tradeOrder.setPayMoney(payMoney);
        tradeOrder.setPackageType(packageType);
        tradeOrder.setOrderStatus((short) OrderStatus.TO_PROCESS);
        tradeOrder.setLineTime(new Date());
        tradeOrder.setShelfId(11L);
        tradeOrder.setTryCnt((short) 0);
        tradeOrder.setCounterFee(new BigDecimal(1));
        tradeOrder.setExtraData("11");
        tradeOrder.setOrderType(orderType);
        iTradeOrderMapper.insert(tradeOrder);

        TradeFlow tradeFlow = new TradeFlow();
        tradeFlow.setOrderId(tradeOrder.getOrderId());
        tradeFlow.setBeginTime(new Date());
        tradeFlow.setChargeStatus((short) OrderStatus.TO_PROCESS);

        iTradeFlowMapper.insert(tradeFlow);
    }

    public void SGPROCESS(TradeOrder tradeOrder, TradeFlow tradeFlow){
        tradeOrder.setOrderStatus((short) OrderStatus.SG_PROCESS);
        tradeFlow.setChargeStatus((short) OrderStatus.SG_PROCESS);

        iTradeOrderMapper.updateOrderState(tradeOrder);
        iTradeFlowMapper.updateState(tradeFlow);
    }


    public void UNKNOWN(TradeOrder tradeOrder, TradeFlow tradeFlow){
        tradeOrder.setOrderStatus((short) OrderStatus.UNKNOWN);
        tradeFlow.setChargeStatus((short) OrderStatus.UNKNOWN);

        iTradeOrderMapper.updateOrderState(tradeOrder);
        iTradeFlowMapper.updateState(tradeFlow);
    }

    public void SUCCESS(TradeOrder tradeOrder,TradeFlow tradeFlow){
        tradeOrder.setOrderStatus((short) OrderStatus.SUCCESS);
        tradeFlow.setChargeStatus((short) OrderStatus.SUCCESS);
        iTradeOrderMapper.updateOrderState(tradeOrder);
        iTradeFlowMapper.updateState(tradeFlow);

//        INTO TRADE_NOTIFY

        TradeNotify tradeNotify = new TradeNotify() ;
        tradeNotify.setOrderId(tradeOrder.getOrderId());
        tradeNotify.setNotifyStatus((short) 1);
        tradeNotify.setNotifyCnt((short) 0);
        tradeNotify.setBeginTime(new Timestamp(System.currentTimeMillis()));
        tradeNotify.setInsertTime(new Timestamp(System.currentTimeMillis()));

        try {
            tradeNotifyMapper.insert(tradeNotify);
        } catch (Exception e) {
            logger.warn("orderid:{} 已经回调过了",tradeOrder.getOrderId(),e);
        }
    }

    public void RECHARGE_FAIL(TradeOrder tradeOrder,TradeFlow tradeFlow){
        String[] sups = tradeOrder.getSupList().split(",");
        String currSup = tradeOrder.getSupId();
        boolean isMatch = false;
        String nextSup = "";
        for(String sup : sups){
            if (StringUtils.equals(sup.split("_")[0],currSup)){
                isMatch = true;
            }else{
                if (isMatch){
                    nextSup = sup.split("_")[0];
                    logger.info("有下一个供货商,orderId:{} . supId:{}",tradeOrder.getOrderId(),nextSup);
                }
            }
        }

        if (StringUtils.isEmpty(nextSup)){

            logger.info("没有下一个供货商了，直接失败,orderId:{}",tradeOrder.getOrderId());
            FAIL(tradeOrder, tradeFlow);
            return ;
        }

        tradeOrder.setSupId(nextSup);
        iTradeOrderMapper.updateOrderSup(tradeOrder);


        tradeFlow.setSupId(nextSup);
        iTradeFlowMapper.updateSup(tradeFlow);

        tradeOrder.setOrderStatus((short) OrderStatus.TO_PROCESS);
        tradeFlow.setChargeStatus((short) OrderStatus.TO_PROCESS);
        iTradeOrderMapper.updateOrderState(tradeOrder);
        iTradeFlowMapper.updateState(tradeFlow);
    }

    public void FAIL(TradeOrder tradeOrder,TradeFlow tradeFlow){

        tradeOrder.setOrderStatus((short) OrderStatus.SG_PROCESS);
        tradeFlow.setChargeStatus((short) OrderStatus.SG_PROCESS);
        iTradeOrderMapper.updateOrderState(tradeOrder);
        iTradeFlowMapper.updateState(tradeFlow);


//        tradeOrder.setOrderStatus((short) OrderStatus.FAIL);
//        tradeFlow.setChargeStatus((short) OrderStatus.FAIL);
//        iTradeOrderMapper.updateOrderState(tradeOrder);
//        iTradeFlowMapper.updateState(tradeFlow);
//
//        TradeNotify tradeNotify = new TradeNotify() ;
//        tradeNotify.setOrderId(tradeOrder.getOrderId());
//        tradeNotify.setNotifyStatus((short) 1);
//        tradeNotify.setNotifyCnt((short) 0);
//        tradeNotify.setBeginTime(new Timestamp(System.currentTimeMillis()));
//        tradeNotify.setInsertTime(new Timestamp(System.currentTimeMillis()));
//
//        try {
//            tradeNotifyMapper.insert(tradeNotify);
//        } catch (Exception e) {
//            logger.warn("orderid:{} 已经回调过了",tradeOrder.getOrderId(),e);
//        }
    }
}
